package com.controller;

import com.po.User;
import com.service.UserService;
import com.vo.CourseDTO;
import com.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.contants.PageConstants.DEFAULT_PAGE_NUM;
import static com.contants.PageConstants.DEFAULT_PAGE_SIZE;

/**
 * @author Te
 * @date At 2018.5.10
 */
@Controller
@RequestMapping(value = "/user")
public class UserController2 {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    @Qualifier(value = "userService")
    private UserService userService;

    /**
     * 用户注册
     *
     * @param user user
     * @return register success  redirect to login html
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@ModelAttribute User user) {
        try {
            userService.register(user);
        } catch (Exception e) {
            LOGGER.error("user register failure");
            return "register";
        }
        return "login";
    }

    /**
     * 用户注销
     *
     * @param request request请求对象
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("currentuser");
        return "redirect:/login";
    }

    /**
     * 用户的个人中心
     *
     * @return List<Course></>
     */
    @GetMapping(value = "/index")
    public String index(HttpServletRequest request, Model model) {

        User user = null;
        try {
            //TODO current user ? Camel Name
            user = (User) request.getSession().getAttribute("currentuser");
        } catch (Exception e) {
            LOGGER.error("getCourses -> cast error , Are you sure current user is User class");
        }

        if (user == null) {
            return "login";
        }
        UserVO userVO = userService.mapUser2UserVO(user);
        List<CourseDTO> courses = userService.getCourses(user.getId(), 1, 5);
        List<CourseDTO> events = userService.getEvents(user.getId(), 1, 5);

        model.addAttribute("userVO", userVO);
        model.addAttribute("courses", courses);
        model.addAttribute("events", events);

        return "user/user_index";
    }

    /**
     * 返回当前登录用户选修事件（分页）
     *
     * @return List<Course></>
     */
    @GetMapping(value = "/events")
    public String getEvents(HttpServletRequest request,
                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "5") int pageSize, Model model) {

        User user = null;
        try {
            user = (User) request.getSession().getAttribute("currentuser");
        } catch (Exception e) {
            LOGGER.error("getEvents -> cast error , Are you sure current user is User class");
        }

        if (user == null) {
            return "login";
        }

        List<CourseDTO> events = userService.getEvents(user.getId(), pageNum, pageSize);
        int total = userService.getTotalEventNum();
        model.addAttribute("currentPage", pageNum);
        model.addAttribute("events", events);
        model.addAttribute("totalSize",total);
        model.addAttribute("totalPage", total / pageSize + 1);
        return "user/user_events";
    }


    /**
     * 返回当前登录用户选修课程（分页）
     *
     * @return List<Course></>
     */
    @GetMapping(value = "/courses")
    public String getCourses(HttpServletRequest request,
                             @RequestParam(value = "pageNum", required = false, defaultValue = DEFAULT_PAGE_NUM) int pageNum,
                             @RequestParam(value = "pageSize", required = false, defaultValue = DEFAULT_PAGE_SIZE) int pageSize, Model model) {

        User user = null;
        try {
            user = (User) request.getSession().getAttribute("currentuser");
        } catch (Exception e) {
            LOGGER.error("getCourses -> cast error , Are you sure current user is User class");
        }

        if (user == null) {
            return "login";
        }

        List<CourseDTO> courses = userService.getCourses(user.getId(), pageNum, pageSize);
        int total = userService.getTotalCourseNum();
        model.addAttribute("currentPage", pageNum);
        model.addAttribute("courses", courses);
        model.addAttribute("totalSize",total);
        model.addAttribute("totalPage", total / pageSize + 1);
        return "user/user_course";
    }

    @GetMapping("/edit")
    public String edit() {
        return "user/change_password";
    }

    /**
     * 修改用户密码
     *
     * @param request  HttpServletRequest request
     * @param password new password
     * @return update success,return success html,otherwise pop error message,return current html
     */
    @PostMapping(value = "/update_password")
    public String update(HttpServletRequest request, String password) {
        User user = null;
        try {
            user = (User) request.getSession().getAttribute("currentuser");
        } catch (Exception e) {
            LOGGER.error("update -> cast error , Are you sure current user is User class");
        }

        if (user == null) {
            return "login";
        }

        userService.updatePassword(user.getId(), password);

        return "user/change_ok";
    }

}
